package cn.itguy.mobileguard.widget;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ProgressBar;

public class AlarmView extends ProgressBar {

	public static final int STATE_PROGRESS_STOP = 0;
	public static final int STATE_PROGRESS_UP   = 1;
	public static final int STATE_PROGRESS_DOWN = 2;
	
	private int resId;

	private int state = STATE_PROGRESS_STOP;
	
	private AlarmListener alarmListener;

	public AlarmView(Context context, AttributeSet attrs) {
		super(context, attrs);
		resId = attrs.getAttributeResourceValue(
				"http://schemas.android.com/apk/res/android",
				"progressDrawable", 0);
	}

	public AlarmListener getAlarmListener() {
		return alarmListener;
	}

	public void setAlarmListener(AlarmListener alarmListener) {
		this.alarmListener = alarmListener;
	}

	@Override
	protected synchronized void onMeasure(int widthMeasureSpec,
			int heightMeasureSpec) {
		Drawable d = getResources().getDrawable(resId);
		int dw = d.getIntrinsicWidth();
		int dh = d.getIntrinsicHeight();
		setMeasuredDimension(resolveSize(dw, widthMeasureSpec),
				resolveSize(dh, heightMeasureSpec));
	}

	public void start() {
		state = STATE_PROGRESS_UP;
		removeCallbacks(runnable);
		post(runnable);
	}
	
	public void stop() {
		state = STATE_PROGRESS_DOWN;
		removeCallbacks(runnable);
		post(runnable);
	}
	
//	@Override
//	public boolean onTouchEvent(MotionEvent event) {
//		int action = event.getAction();
//		switch (action) {
//		case MotionEvent.ACTION_DOWN:
//			state = STATE_PROGRESS_UP;
//			removeCallbacks(runnable);
//			post(runnable);
//			return true;
//		case MotionEvent.ACTION_UP:
//		case MotionEvent.ACTION_CANCEL:
//			if (state != STATE_PROGRESS_STOP) {
//				state = STATE_PROGRESS_DOWN;
//				removeCallbacks(runnable);
//				post(runnable);
//			}
//			return true;
//		}
//		return super.onTouchEvent(event);
//	}
	
	private Runnable runnable = new Runnable() {

		@Override
		public void run() {
			int p = getProgress();
			switch (state) {
			case STATE_PROGRESS_STOP:
				removeCallbacks(this);
				break;
			case STATE_PROGRESS_UP:
				if (p == getMax()) {
					state = STATE_PROGRESS_STOP;
					if (alarmListener != null) {
						alarmListener.onAlarmStarted();
					}
				} else {
					setProgress(p + 1);
				}
				postDelayed(this, 5);
				break;
			case STATE_PROGRESS_DOWN:
				if (p == 30) {
					state = STATE_PROGRESS_STOP;
					if (alarmListener != null) {
						alarmListener.onAlarmStopped();
					}
				} else {
					setProgress(p - 1);
				}
				postDelayed(this, 5);
				break;
			}
		}
	};

	public interface AlarmListener {

		void onAlarmStarted();
		
		void onAlarmStopped();

	}

}
